<template>
  <div class="app-container">
    <h3>组卷信息</h3>
    <el-card style="margin-top: 20px">
      <div style="float: right; font-weight: bold; color: #ff0000">
        试卷总分：{{ examDto.totalScore }}分
      </div>

      <div>
        <el-button
          class="filter-item"
          size="small"
          type="primary"
          icon="el-icon-plus"
          @click="handleAdd"
        >
          添加题库
        </el-button>

        <el-table
          :data="examDto.examRepos"
          :border="false"
          empty-text="请点击上面的`添加题库`进行设置"
          style="width: 100%; margin-top: 15px"
        >
          <el-table-column label="题库" width="200">
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.repoId"
                placeholder="请选择"
                @change="repoChange(scope.row)"
              >
                <el-option
                  v-for="item in repoList"
                  :key="item.id"
                  :label="item.title"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="单选数量" align="center">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.radioCount"
                :min="0"
                :max="scope.row.totalRadio"
                :controls="false"
                style="width: 60%"
              />
              / {{ scope.row.totalRadio }}
            </template>
          </el-table-column>

          <el-table-column label="单选分数" align="center">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.radioScore"
                :min="0"
                :controls="false"
                style="width: 60%"
              />
            </template>
          </el-table-column>

          <el-table-column label="多选数量" align="center">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.multiCount"
                :min="0"
                :max="scope.row.totalMulti"
                :controls="false"
                style="width: 60%"
              />
              / {{ scope.row.totalMulti }}
            </template>
          </el-table-column>

          <el-table-column label="多选分数" align="center">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.multiScore"
                :min="0"
                :controls="false"
                style="width: 60%"
              />
            </template>
          </el-table-column>

          <el-table-column label="判断题数量" align="center">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.judgeCount"
                :min="0"
                :max="scope.row.totalJudge"
                :controls="false"
                style="width: 60%"
              />
              / {{ scope.row.totalJudge }}
            </template>
          </el-table-column>

          <el-table-column label="判断题分数" align="center">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.judgeScore"
                :min="0"
                :controls="false"
                style="width: 60%"
              />
            </template>
          </el-table-column>

          <el-table-column label="简答题数量" align="center">
            <template slot-scope="scope">
              <el-input-number
                style="width: 60%"
                v-model="scope.row.saqCount"
                :max="scope.row.totalSaq"
                :min="0"
                :controls="false"
              />
              / {{ scope.row.totalSaq }}
            </template>
          </el-table-column>

          <el-table-column label="简答题分数" align="center">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.saqScore"
                :min="0"
                :controls="false"
                style="width: 60%"
              />
            </template>
          </el-table-column>

          <el-table-column label="删除" align="center" width="80px">
            <template slot-scope="scope">
              <el-button
                type="danger"
                icon="el-icon-delete"
                circle
                @click="removeItem(scope.$index)"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <h3>考试配置</h3>
    <el-card style="margin-top: 20px">
      <el-form
        ref="examDto"
        :model="examDto"
        label-position="left"
        label-width="120px"
      >
        <el-form-item label="考试名称" prop="title">
          <el-input v-model="examDto.title" />
        </el-form-item>

        <el-form-item label="考试描述" prop="content">
          <el-input v-model="examDto.content" type="textarea" />
        </el-form-item>

        <el-form-item label="总分数" prop="totalScore">
          <el-input-number :value="examDto.totalScore" disabled />
        </el-form-item>

        <el-form-item label="及格分" prop="qualifyScore">
          <el-input-number
            v-model="examDto.qualifyScore"
            :max="examDto.totalScore"
          />
        </el-form-item>

        <el-form-item label="考试时长(分钟)" prop="totalTime">
          <el-input-number v-model="examDto.totalTime" />
        </el-form-item>

        <el-form-item label="是否限时">
          <el-checkbox v-model="examDto.timeLimit" />
        </el-form-item>

        <el-form-item
          v-if="examDto.timeLimit"
          label="考试时间"
          prop="totalTime"
        >
          <el-date-picker
            v-model="dateValues"
            type="datetimerange"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
    </el-card>

    <h3>权限配置</h3>
    <el-card style="margin-top: 20px">
      <el-radio-group v-model="examDto.openType" style="margin-bottom: 20px">
        <el-radio :label="1" border>完全公开</el-radio>
        <el-radio :label="2" border>部门开放</el-radio>
        <el-radio :label="3" border>指定人员</el-radio>
      </el-radio-group>

      <el-alert
        v-if="examDto.openType === 1"
        title="开放的，任何人都可以进行考试！"
        type="warning"
      />

      <div v-if="examDto.openType === 2">
        <el-input v-model="filterText" placeholder="输入关键字进行过滤" />

        <el-tree
          ref="tree"
          empty-text=" "
          :data="treeData"
          default-expand-all
          show-checkbox
          node-key="id"
          :default-checked-keys="examDto.departIds"
          :props="defaultProps"
          :filter-node-method="filterNode"
          @check-change="handleCheckChange"
        />
      </div>
    </el-card>

    <div style="margin-top: 20px">
      <el-button type="primary" @click="handleSave">保存</el-button>
    </div>
  </div>
</template>
<script>
import { fetchRepos } from '@/api/repo'
import { tree } from '@/api/dept'
import { save } from '@/api/exam'
export default {
  data () {
    return {
      filterText: '',
      treeData: [], //部门数据
      dateValues: [],
      repoList: [],
      examDto: {
        examRepos: [],
        departIds: [],
        userIds: []
      },
      defaultProps: {
        children: 'children',
        label: 'label'
      }
    }
  },
  watch: {
    'examDto.examRepos': {
      handler (newVal, oldVal) {
        var totalScore = 0
        newVal.forEach(item => {
          console.log(item.radioCount * item.radioScore)
          totalScore += item.radioCount * item.radioScore
          totalScore += item.multiCount * item.multiScore
          totalScore += item.judgeCount * item.judgeScore
          totalScore += item.saqCount * item.saqScore
        })
        this.examDto.totalScore = totalScore

        //强制刷新试图
        this.$forceUpdate()
      },
      deep: true
    },
    dateValues: {
      handler () {
        console.log('????????????')
        this.examDto.startTime = this.dateValues[0]
        this.examDto.endTime = this.dateValues[1]
      }
    },
    filterText (val) {
      this.$refs.tree.filter(val)
    }
  },
  methods: {
    handleCheckChange (a, b, c) {
      var nodes = this.$refs.tree.getCheckedNodes()
      console.log(nodes)
      var departIds = []
      nodes.forEach(node => {
        departIds.push(node.id)
      })

      this.examDto.departIds = departIds
    },
    handleAdd () {
      this.examDto.examRepos.push({
        repoId: '',
        radioCount: 0,
        radioScore: 0,
        multiCount: 0,
        multiScore: 0,
        judgeCount: 0,
        judgeScore: 0,
        saqCount: 0,
        saqScore: 0
      })
    },
    removeItem (index) {
      this.examDto.examRepos.splice(index, 1)
    },
    findRepoList () {
      fetchRepos().then(res => {
        this.repoList = res.data
      })
    },
    findDepart () {
      tree().then(res => {
        console.log(res)
        this.treeData = res.data
      })
    },

    repoChange (item) {
      var repoEntity = {}
      this.repoList.forEach(repo => {
        if (repo.id == item.repoId) {
          repoEntity = repo
        }
      })

      item.totalRadio = repoEntity.radioCount
      item.totalMulti = repoEntity.multiCount
      item.totalJudge = repoEntity.judgeCount
      item.totalSaq = repoEntity.saqCount
    },
    handleSave () {
      this.examDto.timeLimit = this.examDto.timeLimit ? 1 : 0
      save(this.examDto).then(res => {
        this.$message({
          type: res.code == 0 ? 'success' : 'error',
          message: res.msg
        })
        // 路由跳转 列表页
        if (res.code == 0) {
          this.$router.push({ path: '/exam/list' })
        }
      })
    },
    filterNode (value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    }
  },
  created () {
    this.findRepoList()

    //获取部门数据
    this.findDepart()
  }
}
</script>
